package com.facebook.android;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class FQLQuery extends Dialog {

    private EditText mFQLQuery;
    private TextView mFQLOutput;
    private Button mSubmitButton;
    private Activity activity;
    private Handler mHandler;
    private ProgressDialog dialog;

    public FQLQuery(Activity activity) {
        super(activity);
        this.activity = activity;
        setTitle(R.string.fqlquery);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandler = new Handler();

        setContentView(R.layout.fql_query);
        LayoutParams params = getWindow().getAttributes();
        params.width = LayoutParams.FILL_PARENT;
        params.height = LayoutParams.FILL_PARENT;
        getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);

        mFQLQuery = (EditText) findViewById(R.id.fqlquery);
        mFQLOutput = (TextView) findViewById(R.id.fqlOutput);
        mSubmitButton = (Button) findViewById(R.id.submit_button);

        mSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(mFQLQuery.getWindowToken(), 0);
                dialog = ProgressDialog.show(FQLQuery.this.activity, "",
                        FQLQuery.this.activity.getString(R.string.please_wait), true, true);
                /*
                 * Source tag: fql_query_tag
                 */
                String query = mFQLQuery.getText().toString();
                
                
                
                
                
                
                // ====== Begin code to send to server.

             	 Date d = new Date();
             	 
             	
             	 JSONObject jsonObjSend = new JSONObject();
                  try {
                 	 jsonObjSend.put("facebookID", Utility.userUID); // Need to put user's FB ID in here.
                 	 jsonObjSend.put("userName", Hackbook.userName); 
          			jsonObjSend.put("venueID", Hackbook.venueID); // put the checkin ID here.
          			jsonObjSend.put("venueName", Hackbook.venueName);
          			jsonObjSend.put("time", Hackbook.time);
          			jsonObjSend.put("rating", "3"); // user's rating goes here.
         			jsonObjSend.put("comments", query);  // user's comments go here.
          		} catch (JSONException e1) {
          			// TODO Auto-generated catch block
          			e1.printStackTrace();
          		}
             	
             	URI uri = null;
                 try {
         			uri = new URI("https://stark-wind-4492.herokuapp.com/checkin");
         			java.lang.System.out.println("foo");
         			java.lang.System.out.println(uri);
         			
         	        
                 } catch (URISyntaxException e) {
         			// TODO Auto-generated catch block
         			e.printStackTrace();
         		}
                 
      			java.lang.System.out.println("bar");
      			java.lang.System.out.println(uri);
                 
                 
                 
                 
                 HttpClient client = new DefaultHttpClient();
                 HttpPost httpPostRequest = new HttpPost(uri);
                 httpPostRequest.setHeader("User-Agent", "com.fontanilla.anthony");
                 httpPostRequest.setHeader("Accept", "application/json");
                 httpPostRequest.setHeader("Content-Type", "application/json");
                 
                 StringEntity se = null;
                 try {
         			se = new StringEntity(jsonObjSend.toString());
         		} catch (UnsupportedEncodingException e) {
         			// TODO Auto-generated catch block
         			e.printStackTrace();
         		}
                 httpPostRequest.setEntity(se);
                 HttpResponse response = null;
                 try {
         			response = client.execute(httpPostRequest);
         		} catch (ClientProtocolException e) {
         			// TODO Auto-generated catch block
         			e.printStackTrace();
         		} catch (IOException e) {
         			// TODO Auto-generated catch block
         			e.printStackTrace();
         		}
                 
                 BasicResponseHandler responseHandler = new BasicResponseHandler();
                 String strResponse = null;
                 if (response != null) {
                     try {
                         strResponse = responseHandler.handleResponse(response);
                     } catch (HttpResponseException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                     } catch (IOException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                     }
                 }
                 Log.e("HTTP PUT", "Response: " + strResponse);

                 // ====== HTTP PUT to server complete!
                
                
                
                
                Bundle params = new Bundle();
                params.putString("method", "fql.query");
                params.putString("query", query);
                Utility.mAsyncRunner.request(null, params, new FQLRequestListener());
            }
        });
    }

    public class FQLRequestListener extends BaseRequestListener {

        @Override
        public void onComplete(final String response, final Object state) {
            dialog.dismiss();
            /*
             * Output can be a JSONArray or a JSONObject.
             * Try JSONArray and if there's a JSONException, parse to JSONObject
             */
            try {
                JSONArray json = new JSONArray(response);
                setText(json.toString(2));
            } catch (JSONException e) {
                try {
                    /*
                     * JSONObject probably indicates there was some error
                     * Display that error, but for end user you should parse the
                     * error and show appropriate message
                     */
                    JSONObject json = new JSONObject(response);
                    setText(json.toString(2));
                } catch (JSONException e1) {
                    setText(activity.getString(R.string.exception) + e1.getMessage());
                }
            }
        }

        public void onFacebookError(FacebookError error) {
            dialog.dismiss();
            setText(activity.getString(R.string.facebook_error) + error.getMessage());
        }
    }

    public void setText(final String txt) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mFQLOutput.setText(txt);
                mFQLOutput.setVisibility(View.VISIBLE);
            }
        });
    }
}
